$(document).ready(function () {
    const urlParams = new URLSearchParams(window.location.search);
    const type = urlParams.get('type');
    if (type === 'sales') {
        switchTab('sales');
        fetchRankings('best_selling', '.course-content#sales', 'sales_count');
    } else {
        switchTab('study');
        fetchRankings('most_studied', '.course-content#study', 'student_count');
    }

    // 切换榜单的函数
    function switchTab(tabName) {
        $('.tab').removeClass('active');
        $(`#${tabName}`).addClass('active');
        $('.course-content').hide();
        $(`#${tabName}-data`).parent().show();
    }

    // 为tab绑定点击事件，实现切换功能
    $('.tabs').on('click', 'div.tab', function () {
        const tabName = $(this).data('tab');
        switchTab(tabName);
        if (tabName === 'sales') {
            fetchRankings('best_selling', '.course-content#sales', 'sales_count');
        } else {
            fetchRankings('most_studied', '.course-content#study', 'student_count');
        }
    });

    // 获取并更新排行榜数据的函数
    function fetchRankings(boardType, targetSelector, countField) {
        $.ajax({
            type: 'POST',
            url: `http://10.2.1.17:8099/EXOnline/font/courses?method=leaderboard&boardType=${boardType}`,
            success: function (res) {
                console.log(res);
                const courses = boardType === 'best_selling' ? res.data.filter(course => course.course_price > 0) : res.data;
                updateRankings(courses, targetSelector, countField);
            },
            error: function (error) {
                console.log(error);
            }
        });
    }

    // 更新排行榜的函数
    function updateRankings(data, targetSelector, countField) {
        const courseList = $(targetSelector).find('.course-list');
        courseList.empty();

        data.forEach((course, index) => {
            const courseItem = `
                <a href="#" class="course-item">
                    <div class="rank-number">${index + 1}</div>
                    <div class="course-image">
                        <img src="img/diushi.jpeg" alt="课程图片">
                    </div>
                    <div class="course-info">
                        <div class="course-title">${course.course_name}</div>
                        <div class="course-price">¥${course.course_price}</div>
                        <div class="student-count">${countField === 'student_count' ? course.student_count : course.sales_count}人在学</div>
                    </div>
                </a>
            `;
            courseList.append(courseItem);
        });
    }


});